class HostTrans:
	def __init__(self, confdir):
		self.conf = confdir
		self.__transHash = {}
		self.Startwith = {}
		self.Endwith = {}
		self.INwith = {}
		self.iswith = {}
		self.ReadConf()
		self.ConvertFunc()


	def ReadConf(self):
		''' Fmt: *.sina.com.cn\tSinaInside\n '''
		f = open('%s/hostrans.conf' % self.conf)
		for line in f:
			hostpattern, classify = line.strip().split('\t')
			self.__transHash[hostpattern] = classify

	def ConvertFunc(self):
		for keys in self.__transHash:
			if keys.count('*') == 1:
				if keys.endswith('*'):
					self.Startwith[keys[:keys.index('*')]] = keys
				elif keys.startswith('*'):
					self.Endwith[keys[keys.index('*')+2:]] = keys
			elif keys.count('*') > 1:
				self.INwith[keys[keys.index('*')+1:keys.rindex('*')]] = keys
			else:
				self.iswith[keys] = keys

	def CompareFunc(self, cline):
		line = self.ToConvert(cline)
		if self.iswith.has_key(line): return self.__transHash[line]
		for cmpkey in self.Endwith:
			if line.endswith(cmpkey):
				''' Second Lvl hostname: auto.sina.com.cn '''
				subname = line[:line.rindex(cmpkey)-1]
				return '%s|%s' % (self.__transHash[self.Endwith[cmpkey]], subname)
		for cmpkey in self.Startwith:
			if line.startswith(cmpkey):
				''' Special Host '''
				#return cmpkey
				return '%s' % self.__transHash[self.Startwith[cmpkey]]

		for cmpkey in self.INwith:
			if cmpkey in line:
				#return cmpkey[1:]
				return '%s' % self.__transHash[self.INwith[cmpkey]]

		if line == '-': return 'DirectIN'

		return line

	def ToConvert(self, line):
		if 'http://' in line:
			if '/' in line[7:]:
				return line[7:line.index('/', 8)].lower()
			#elif line.endswith('.sina.com.cn'):
			#	return line[7:].lower()
			else:
				return line[7:].lower()
		else:
			return '-'
